/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package me.panpf.sketch.sample.widget.fraction;

import me.panpf.sketch.Sketch;
import me.panpf.sketch.SketchImageView;
import me.panpf.sketch.sample.ResourceTable;
import me.panpf.sketch.util.Base64;
import me.panpf.sketch.util.TextUtils;
import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;
import ohos.media.image.ImageSource;
import ohos.media.image.SourceDataMalformedException;
import ohos.media.image.common.Size;
import ohos.system.DeviceInfo;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Base64ImageTestFraction
 */
public class Base64ImageTestFraction extends Fraction {

    private SketchImageView mImageView;

    /**
     * SCHEME
     */
    public static final String SCHEME = "data:image/";

    @Override
    protected Component onComponentAttached(LayoutScatter scatter, ComponentContainer container, Intent intent) {
        Component component = scatter.parse(ResourceTable.Layout_base64_test_fraction, container, false);
        return component;
    }

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        TextField textField = (TextField) getComponent().findComponentById(ResourceTable.Id_edit_base64Test);
        mImageView = (SketchImageView) getComponent().findComponentById(ResourceTable.Id_image_base64Test);

        textField.addTextObserver((s1, i0, i1, i2) -> showImage(s1));

        try {
            String url = getFractionAbility().getResourceManager().getElement(ResourceTable.String_base64Url).getString();
            textField.setText(url);
        } catch (IOException | NotExistException | WrongTypeException ex) {
            ex.printStackTrace();
        }

    }

    private void showImage(String imageText) {
        if (match(imageText)) {
            InputStream inputStream = new ByteArrayInputStream(Base64.decode(getUriContent(imageText), Base64.DEFAULT));
            try {
                ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
                ImageSource imageSource = ImageSource.create(inputStream, sourceOptions);
                ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
                Size size = imageSource.createPixelmap(null).getImageInfo().size;
                Double aspectRatios = size.width / (double) size.height;
                int width;
                if (DeviceInfo.getModel().startsWith("ELS")) {
                    width = 530;
                } else {
                    width = 490;
                }
                decodingOptions.desiredSize = new Size(width, (int) (width / aspectRatios));
                ComponentContainer.LayoutConfig layoutConfig = mImageView.getLayoutConfig();
                layoutConfig.width = width;
                layoutConfig.height = (int) (width / aspectRatios);
                mImageView.setLayoutConfig(layoutConfig);
                mImageView.getOptions().setShapeSize(width, (int) (width / aspectRatios));
                Sketch.with(getFractionAbility()).display(imageText, mImageView).commit();

                return;
            } catch (IllegalArgumentException ex) {
                ex.printStackTrace();
            } catch (SourceDataMalformedException ex) {
                ex.printStackTrace();
            } finally {
                try {
                    inputStream.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    /**
     * match
     * @param uri
     * @return boolean
     */
    protected boolean match(String uri) {
        return !TextUtils.isEmpty(uri) && uri.startsWith(SCHEME);
    }

    /**
     * getUriContent
     * @param uri
     * @return String
     */
    public String getUriContent(String uri) {
        return !TextUtils.isEmpty(uri) ? uri.substring(uri.indexOf(";") + ";base64,".length()) : uri;
    }

}
